package com.zx.stock.thread;

import com.zx.stock.common.Const;
import com.zx.stock.entity.Stock;
import com.zx.stock.entity.StockAgency;
import com.zx.stock.mapper.StockAgencyMapper;
import com.zx.stock.utils.HttpsUtil;
import com.zx.stock.utils.JSONUtil;
import com.zx.stock.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class AgencyThread implements Runnable{


    List<StockAgency> stockList;
    StockAgencyMapper stockAgencyMapper;

    public AgencyThread(List<StockAgency> stockList,StockAgencyMapper stockAgencyMapper){
       this.stockList = stockList;
       this.stockAgencyMapper = stockAgencyMapper;
    }

    @Override
    public void run(){

        if (stockList!=null && !stockList.isEmpty()){

            List<StockAgency> rsList = new ArrayList<>();
            for(StockAgency item:stockList){
                boolean success= findByIcbc(item);
                if (success){
                    rsList.add(item);
                }
            }
            for (StockAgency st:rsList){
                log.info("code:{},name={},\n",st.getCode(),st.getName());
            }
        }

    }
    private boolean findByIcbc(StockAgency entity){

        //String url = "http://data.eastmoney.com/dataapi/zlsj/detail";

        String date = "2020-12-31";

        String url = String.format(entity.getLink(),date);



        String jsonStr = HttpsUtil.doGet(url);
        log.info("请求结果:{}",jsonStr);


        if (!StringUtil.isEmpty(jsonStr)){

            Map<String,Object> rsMap = JSONUtil.jsonToMap(jsonStr);
            if (rsMap!=null && rsMap.get("data")!=null){
                List<Map<String,Object>> arrList = (List<Map<String,Object>>)rsMap.get("data");

                if (arrList!=null && arrList.size()>0){

                    StockAgency agency = new StockAgency();
                    agency.setId(entity.getId());
                    agency.setContent(jsonStr);
                    agency.setReportDate(date);
                    agency.setMtime(new Date());
                    agency.setStatus(Const.Y);
                    stockAgencyMapper.update(agency);
                }

            }



        }
        /**
         *

         http://data.eastmoney.com/dataapi/zlsj/detail?SHType=0&SHCode=&SCode=300100&ReportDate=2020-06-30&sortField=SHCode&sortDirec=1&pageNum=1&pageSize=30

        String url = String.format("http://data.eastmoney.com/zlsj/detail/%s.html",entity.getCode());
        String jsonStr = HttpsUtil.doGet(url);
         **/
        if (!StringUtil.isEmpty(jsonStr) && jsonStr.contains("工商")){
            return true;
        }
        return false;

    }
}
